package com.arron.myhash;

/**
 * @Classname MyHashMap
 * @Date 2020/9/4 0:05
 * @Created by 刘
 *
 * 手写一个hashmap
 *
 */
public class MyHashMap<k,v> {

    private Integer CAPACITY = 8;
    private static Integer size = 0;
    private Entry<k,v>[] table;

    /**
     * 实例化的时候创建数组容器
     * @param capacity
     */
    public MyHashMap(Integer capacity) {
        if (capacity > CAPACITY){
            this.table = new Entry[capacity];
        }else {
            this.table = new Entry[CAPACITY];
        }

    }

    public MyHashMap() {
        this(0);
    }

    public int size() {
        return size;
    }


    public v get(k key) {

        int hashCode = key.hashCode();
        int index = hashCode%table.length;

        //循环判断插入的key是否相同
        for (Entry<k,v> entry = table[index];entry!=null;entry= entry.next) {
            if (entry.k.equals(key)){
                return entry.v;
            }
        }

        return null;
    }

    public v put(k key, v value) {

        int hashCode = key.hashCode();
        int index = hashCode%table.length;

        //完成赋值
        addEntry(key, value, index);

        //循环判断插入的key是否相同,相同就覆盖原来的value，并返回oldValue
        for (Entry<k,v> entry = table[index];entry!=null;entry= entry.next) {
            if (entry.k.equals(key)){
                v oldValue = table[index].v;
                table[index].v=value;
                return oldValue;
            }
        }

        return null;
    }

    /**
     * 将entry值加到数组中
     * @param key
     * @param value
     * @param index
     */
    private void addEntry(k key, v value, int index) {
        table[index] = new Entry<>(key, value,table[index]);
        size++;
    }

    class Entry<k,v>{
        public k k;
        public v v;
        public Entry<k,v> next;

        public Entry(k k, v v, Entry<k, v> next) {
            this.k = k;
            this.v = v;
            this.next = next;
        }
    }


}
